# coding:utf-8
import configparser
import os

from selenium import webdriver
import time


class Zhihu:
    def __init__(self):
        self.url = 'https://www.zhihu.com/#signin'
        self.driver = None

    def login(self):
        self.driver = webdriver.Chrome()
        # 访问登录界面
        self.driver.get(self.url)
        self.driver.implicitly_wait(10)
        # # 切换登录界面
        # el_login_switch = driver.find_element_by_xpath('//a[@class="AppHeader-authLink"]')
        # el_login_switch.click()
        # time.sleep(3)
        # 点击登录
        _el_login = self.driver.find_element_by_xpath('//div[@class="SignContainer-switch"]/span')
        _el_login.click()
        time.sleep(3)
        # 输入账号
        _user_pswd_cfg = os.environ['user_pswd']
        _cf = configparser.ConfigParser()
        _cf.read(_user_pswd_cfg)
        _user = _cf.get('zhihu', 'zhihu_user')
        _pswd = _cf.get('zhihu', 'zhihu_pswd')
        _el_user = self.driver.find_element_by_xpath('//input[@name="username"]')
        _el_user.send_keys(_user)
        # 输入密码
        _el_pwd = self.driver.find_element_by_xpath('//input[@name="password"]')
        _el_pwd.send_keys(_pswd)
        # 点击登陆
        _el_sub = self.driver.find_element_by_xpath('//form/button')
        _el_sub.click()
        time.sleep(2)
        # TODO 选择验证码
        # 点击登录
        self.driver.close()

    def run(self):
        self.login()


def main():
    zh = Zhihu()
    zh.run()


if __name__ == '__main__':
    main()
